package com.ruoyi.cs.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.utils.HashUtil;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.vo.PageInfoParamVo;
import com.ruoyi.cs.domain.vo.TRollBackVo;
import com.ruoyi.cs.domain.vo.TRollHomePageVo;
import com.ruoyi.cs.domain.vo.TRollVo;
import com.ruoyi.cs.mapper.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.thoughtworks.xstream.mapper.Mapper;
import jdk.nashorn.internal.runtime.arrays.IteratorAction;
import org.omg.CORBA.REBIND;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.cs.service.ITRollService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * ROLL房间信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-03-25
 */
@Service
@SuppressWarnings("all")
public class TRollServiceImpl implements ITRollService 
{
    private static final Logger log = LoggerFactory.getLogger(TRollServiceImpl.class);
    @Autowired
    private TRollMapper tRollMapper;

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private TRollCyMapper tRollCyMapper;

    @Autowired
    private TGoodsMapper tGoodsMapper;

    @Autowired
    private TRechargeMapper tRechargeMapper;

    @Autowired
    private TExchangeMapper tExchangeMapper;

    @Autowired
    private TBackpackMapper tBackpackMapper;

    @Autowired
    private TBalanceChangeMapper tBalanceChangeMapper;

    /**
     * 查询ROLL房间信息
     * 
     * @param rollId ROLL房间信息ID
     * @return ROLL房间信息
     */
    @Override
    public TRoll selectTRollById(String rollId)
    {
        return tRollMapper.selectTRollById(rollId);
    }

    /**
     * 查询ROLL房间所有信息列表
     * 
     * @param tRoll ROLL房间信息
     * @return ROLL房间信息
     */
    @Override
    public List<TRollBackVo> selectTRollList(TRollBackVo tRoll)
    {
        List<TRollBackVo> list = tRollMapper.tRollListBack(tRoll);
        if (list.size() > 0)
        {
            List<String> rollIds = list.stream().map(TRollBackVo::getRollId).collect(Collectors.toList());
            /**统计ROLL房用户参与人数统计*/
            List<Map> mapList = tRollCyMapper.countUserNumGroupRollId(rollIds);
            if (mapList.size() > 0)
            {
                list.stream().forEach(bean -> {
                List<Map> mapList1 = mapList.stream().filter(map -> map.get("rollId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                if (map != null) {
                    bean.setUserNum(map.get("userNum").toString());
                }else {
                    bean.setUserNum("0");
                }
            });
            }else {
                list.stream().forEach(bean -> {
                    bean.setUserNum("0");
                });
            }
            /**统计ROLL房的饰品件数、奖池*/
            List<Map> goodsList = tGoodsMapper.countGoodsNumAndPrice(rollIds);
            if (goodsList.size() > 0) {
                list.stream().forEach(bean -> {
                    List<Map> mapList1 = goodsList.stream().filter(map -> map.get("goodsBelongingId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setGoodsCount(map.get("goodsCount").toString());
                        bean.setGoodsPriceTotal(map.get("goodsPriceTotal").toString());
                    }else {
                        bean.setGoodsCount("0");
                        bean.setGoodsPriceTotal("0");
                    }
                });
            }else {
                list.stream().forEach(bean -> {
                    bean.setGoodsCount("0");
                    bean.setGoodsPriceTotal("0");
                });
            }
        }
        return list;
    }

    /**
     * 新增ROLL房间信息
     * 
     * @param tRoll ROLL房间信息★
     * @return 结果
     */
    @Override
    public Response insertTRoll(TRoll tRoll)
    {
        if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE1)){
            if (StringUtils.isEmpty(tRoll.getRollGzMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛！");
            }

        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE2)) {
            if (StringUtils.isNull(tRoll.getRollCzMk())){
                return Response.fail(Constants.FAILCODE,"请填写充值门槛！");
            }
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE3)) {
            if (tRoll.getRollStartTime() == null || tRoll.getRollEndTime() == null || StringUtils.isNull(tRoll.getRollFwczMk())){
                return Response.fail(Constants.FAILCODE,"请填写时间范围内的充值门槛、充值开始时间、结束时间！");
            }

        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE4)) {
            if (StringUtils.isEmpty(tRoll.getRollGzMk()) || StringUtils.isNull(tRoll.getRollCzMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛、充值门槛！");
            }

        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE5)) {
            if (StringUtils.isEmpty(tRoll.getRollGzMk()) || tRoll.getRollStartTime() == null || tRoll.getRollEndTime() == null || StringUtils.isNull(tRoll.getRollFwczMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛、时间范围内的充值门槛、充值开始时间、结束时间！");
            }
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE6)) {
            if (StringUtils.isEmpty(tRoll.getRollPwd())){
                return Response.fail(Constants.FAILCODE,"请填写ROLL房密码！");
            }
        }else if (tRoll.getDrawPriceType().equals("1")){
            if (StringUtils.isEmpty(tRoll.getCyNumberlimit())) {
                return Response.fail(Constants.FAILCODE,"选择满人后开奖则必须填写参与人数上限！");
            }
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE8)){
            if (StringUtils.isEmpty(tRoll.getRollGzMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛！");
            }
        }
        tRoll.setRollStatus(Constants.ROLLSTATUS0);
        tRoll.setCreateTime(DateUtils.getNowDate());
        String serverSeed = HashUtil.generateServerSeed();
        tRoll.setServerSeed(serverSeed);
        tRollMapper.insertTRoll(tRoll);
        return Response.success();
    }

    /**
     * 修改ROLL房间信息
     * 
     * @param tRoll ROLL房间信息
     * @return 结果
     */
    @Override
    public Response updateTRoll(TRoll tRoll)
    {
        if(tRoll.getRollMkType().equals(Constants.ROLLMKTYPE0)){
            /*如果是无门槛则清空所有条件*/
            tRoll.setRollPwd(null);
            tRoll.setRollGzMk(null);
            tRoll.setRollCzMk(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
            tRoll.setRollStartTime(null);
            tRoll.setRollEndTime(null);
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE1)){
            if (StringUtils.isEmpty(tRoll.getRollGzMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollCzMk(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
            tRoll.setRollStartTime(null);
            tRoll.setRollEndTime(null);
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE2)) {
            if (StringUtils.isNull(tRoll.getRollCzMk())){
                return Response.fail(Constants.FAILCODE,"请填写充值门槛！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollGzMk(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
            tRoll.setRollStartTime(null);
            tRoll.setRollEndTime(null);
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE3)) {
            if (tRoll.getRollStartTime() == null || tRoll.getRollEndTime() == null || StringUtils.isNull(tRoll.getRollFwczMk())){
                return Response.fail(Constants.FAILCODE,"请填写时间范围内的充值门槛、充值开始时间、结束时间！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollGzMk(null);
            tRoll.setRollCzMk(null);
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE4)) {
            if (StringUtils.isEmpty(tRoll.getRollGzMk()) || StringUtils.isNull(tRoll.getRollCzMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛、充值门槛！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
            tRoll.setRollStartTime(null);
            tRoll.setRollEndTime(null);

        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE5)) {
            if (StringUtils.isEmpty(tRoll.getRollGzMk()) || tRoll.getRollStartTime() == null || tRoll.getRollEndTime() == null || StringUtils.isNull(tRoll.getRollFwczMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛、时间范围内的充值门槛、充值开始时间、结束时间！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollCzMk(null);
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE6)) {
            if (StringUtils.isEmpty(tRoll.getRollPwd())){
                return Response.fail(Constants.FAILCODE,"请填写ROLL房密码！");
            }
            tRoll.setRollGzMk(null);
            tRoll.setRollCzMk(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
            tRoll.setRollStartTime(null);
            tRoll.setRollEndTime(null);
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE7)) {
            if (tRoll.getRollStartTime() == null || tRoll.getRollEndTime() == null) {
                return Response.fail(Constants.FAILCODE, "请填写注册时间范围！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollGzMk(null);
            tRoll.setRollCzMk(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
        }else if (tRoll.getDrawPriceType().equals("1")){
            if (StringUtils.isEmpty(tRoll.getCyNumberlimit())) {
                return Response.fail(Constants.FAILCODE,"选择满人后开奖则必须填写参与人数上限！");
            }
        }else if (tRoll.getRollMkType().equals(Constants.ROLLMKTYPE8)){
            if (StringUtils.isEmpty(tRoll.getRollGzMk())){
                return Response.fail(Constants.FAILCODE,"请填写关注门槛！");
            }
            if (tRoll.getRollStartTime() == null || tRoll.getRollEndTime() == null) {
                return Response.fail(Constants.FAILCODE, "请填写注册时间范围！");
            }
            tRoll.setRollPwd(null);
            tRoll.setRollCzMk(null);
            tRoll.setRollFwczMk(new BigDecimal(0));
        }
        tRoll.setUpdateTime(DateUtils.getNowDate());
        tRollMapper.updateTRoll1(tRoll);
        return Response.success();
    }

    /**
     * 批量删除ROLL房间信息
     * 
     * @param rollIds 需要删除的ROLL房间信息ID
     * @return 结果
     */
    @Override
    public int deleteTRollByIds(String[] rollIds)
    {
        int count = tGoodsMapper.bacthTGoodsCountDelete(Constants.GOOGSBLTYPE1,rollIds);
        if (count > 0) {
            return Constants.FAILCODE;
        }
        return tRollMapper.updateTRollDelFlagByIds(Constants.DELETE,rollIds);
    }

    /**
     * 批量停用
     * @param rollIds
     * @return
     */
    @Override
    public int stopTRollByIds(String[] rollIds) {
        int count = tGoodsMapper.bacthTGoodsCount(Constants.SUCCESS,Constants.GOOGSBLTYPE1,rollIds);
        if (count > 0) {
            return Constants.FAILCODE;
        }
        return tRollMapper.updateTRollDelFlagByIds(Constants.FAIL,rollIds);
    }

    /**
     * 批量启用
     * @param rollIds
     * @return
     */
    @Override
    public int enableTRollByIds(String[] rollIds) {
        return tRollMapper.updateTRollDelFlagByIds(Constants.SUCCESS,rollIds);
    }

    /**
     * 删除ROLL房间信息信息
     * 
     * @param rollId ROLL房间信息ID
     * @return 结果
     */
    @Override
    public int deleteTRollById(String rollId)
    {
        return tRollMapper.deleteTRollById(rollId);
    }

    /**
     * 查询所有可展示给前台的ROLL房列表,用户已参与的ROLL可以通过USERID来判断
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> selectTRollListAll(String userId,String rollName) {
        /**展示列表  可用的并且ROLL房状态为已上线或已结束的ROLL房列表信息*/
        List<TRollVo> rollList = new ArrayList<>();
//        if (StringUtils.isNotEmpty(userId)) {
//           rollList = tRollMapper.selectTRollListAll();
//        }else {
//            rollList = tRollMapper.selectTRollListAll1();
//        }
        rollList = tRollMapper.selectTRollListAll(rollName);

        return this.countTRollList(rollList,userId);
    }

    /**
     * 分页查询roll房间列表
     * @param pageInfoParamVo
     * @return
     */
    @Override
    public List<TRollVo> selectTRollPageListAll(PageInfoParamVo pageInfoParamVo) {
        List<TRollVo> rollList = tRollMapper.selectTRollListAll(pageInfoParamVo.getRollName());
        return countTRollPageList(rollList,pageInfoParamVo.getUserId());
    }

    /**
     * 批量获取ROLL房信息
     * @param rollIds
     * @return
     */
    @Override
    public List<TRoll> batchQueryTRollList(String[] rollIds) {
        return tRollMapper.batchQueryTRollList(rollIds);
    }

    /**
     * 单独对数据进行关联配置  统计用户人数、饰品件数、饰品金额
     * @param rollList
     * @param tRoll
     * @return
     */
    @Override
    public  Map<String,Object> countTRollList(List<TRollVo> rollList,String userId) {
        /**判断用户ID是否存在，存在则显示状态,*/
        List<TRollVo> myList = new ArrayList<>();
        if (rollList.size() > 0) {
            List<String> rollIds = rollList.stream().map(TRollVo::getRollId).collect(Collectors.toList());

            if (StringUtils.isNotEmpty(userId)) {
                /**获取用户参与ROLL房信息*/
                List<TRollCy> tRollCyList = tRollCyMapper.selectTRollCyByUserId(userId, rollIds);


                for (TRollVo bean : rollList) {
                    if (Constants.ROLLSTATUS1.equals(bean.getRollStatus())) {
                        if (tRollCyList.size() > 0) {
                            List<TRollCy> tRollCyList1 = tRollCyList.stream().filter(tRollCy -> bean.getRollId().equals(tRollCy.getRollId())).collect(Collectors.toList());
                            if (tRollCyList1.size() > 0) {
                                if (Constants.ROLLSTATUS2.equals(bean.getRollStatus())) {
                                    bean.setUserStatus(Constants.USERROLLSTATUS2);
                                } else {
                                    bean.setUserStatus(Constants.USERROLLSTATUS1);
                                }
                                bean.setUserId(userId);
                            } else {/**表示未加入*/
                                bean.setUserStatus(Constants.USERROLLSTATUS0);
                            }
                        } else {
                            bean.setUserStatus(Constants.USERROLLSTATUS0);
                        }
                    } else {
                        bean.setUserStatus(Constants.USERROLLSTATUS2);
                    }
                }

                /**获取用户参与的ROLL房列表*/

                if (tRollCyList.size() > 0) {
                    tRollCyList.stream().forEach(tRollCy -> {
                        List<TRollVo> tRollList = rollList.stream().filter(rr -> rr.getRollId().equals(tRollCy.getRollId())).collect(Collectors.toList());
                        if (tRollList.size() > 0) {
                            myList.add(tRollList.get(0));
                        }
                    });
                }
            }
            /**统计ROLL房用户参与人数统计*/
            List<Map> mapList = tRollCyMapper.countUserNumGroupRollId(rollIds);
            if (mapList.size() > 0) {
                rollList.stream().forEach(bean -> {
                    List<Map> mapList1 = mapList.stream().filter(map -> map.get("rollId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setUserNum(map.get("userNum").toString());
                    } else {
                        bean.setUserNum("0");
                    }
                });
            } else {
                rollList.stream().forEach(bean -> {
                    bean.setUserNum("0");
                });
            }
            /**统计ROLL房的饰品件数、奖池*/
            List<Map> goodsList = tGoodsMapper.countGoodsNumAndPrice(rollIds);
            if (goodsList.size() > 0) {
                rollList.stream().forEach(bean -> {
                    List<Map> mapList1 = goodsList.stream().filter(map -> map.get("goodsBelongingId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setGoodsCount(map.get("goodsCount").toString());
                        bean.setGoodsPriceTotal(map.get("goodsPriceTotal").toString());
                    } else {
                        bean.setGoodsCount("0");
                        bean.setGoodsPriceTotal("0");
                    }
                });
            } else {
                rollList.stream().forEach(bean -> {
                    bean.setGoodsCount("0");
                    bean.setGoodsPriceTotal("0");
                });
            }
            /**ROLL房对应的排名前三的饰品图片*/
            rollList.stream().forEach(bean -> {
                List<Map> list = tGoodsMapper.rollPicList3(bean.getRollId());
                bean.setList(list);
            });
        }


        /**排序后的ROLL*/
        List<TRollVo> sortList = new ArrayList<>();
        if (rollList != null && rollList.size() > 0) {
            for (TRollVo tRollVo : rollList) {
                TRollVo tRollVo1 = new TRollVo();
                BeanUtils.copyProperties(tRollVo, tRollVo1);
                sortList.add(tRollVo1);
            }
            sortList.sort(Comparator.comparing(TRoll::getRollZdkjTime).reversed());
        }

        /**返回结果*/
        Map<String, Object> result = new HashMap<>();
        result.put("allList", rollList);
        result.put("myList", myList);
        result.put("sortList", sortList);
        return result;

    }

    /**
     * ROLL房详情 饰品列表、参与人列表
     * @param rollId
     * @return
     */
    @Override
    public Response<TRollVo> getRollInfo(String userId,String rollId) {
        /**获取ROLL信息*/
        TRoll tRoll =  tRollMapper.selectTRollById(rollId);
        if(StringUtils.isNull(tRoll)) {
            return Response.fail(Constants.FAILCODE,"参数错误，ROLL房不存在！");
        }
        TRollVo rollVo = new TRollVo();
        BeanUtils.copyProperties(tRoll,rollVo);

        /**获取饰品信息列表*/
        List<TGoods> goodsList = tGoodsMapper.rollGoodsList(rollId);
        /**统计饰品件数、总金额*/
        rollVo.setGoodsCount(Integer.toString(goodsList.size()));
        BigDecimal goodsPriceTotal = new BigDecimal(0);
        if (goodsList.size() > 0) {
            for (TGoods tgood:goodsList) {
                goodsPriceTotal = goodsPriceTotal.add(tgood.getGoodsPrice());
                JSONObject jsonObject = JSON.parseObject(tgood.getRollValueRange());
                tgood.setRollValueRangeObj(jsonObject);
            }
        }
        rollVo.setGoodsPriceTotal(goodsPriceTotal.toString());
        /**获取ROLL房所有用户参与信息列表*/
        List<Map> userMapList = tRollCyMapper.selectTRollCyInfo(null,rollId);
        rollVo.setUserCyList(userMapList);
        /**统计用户参与人数*/
        rollVo.setUserNum(Integer.toString(userMapList.size()));

        /**判断用户ID是否存在，如果存在则判断该房间中用户的状态*/
        if (tRoll.getRollStatus().equals(Constants.ROLLSTATUS1)) {
            if (StringUtils.isNotEmpty(userId)){
                if (userMapList.size() > 0){
                    List<Map> mapList = userMapList.stream().filter(map -> map.get("userId").equals(userId)).collect(Collectors.toList());
                    if (mapList != null && mapList.size()>0) {
                        rollVo.setUserStatus(Constants.USERROLLSTATUS1);
                    }else {
                        rollVo.setUserStatus(Constants.USERROLLSTATUS0);
                    }
                }else {
                    rollVo.setUserStatus(Constants.USERROLLSTATUS0);
                }
            }else {
                rollVo.setUserStatus(Constants.USERROLLSTATUS0);
            }
        }else{
            rollVo.setUserStatus(Constants.USERROLLSTATUS2);
            /**ROLL房中奖记录*/
            List<Map> winningMapList = userMapList.stream().filter(map -> map.get("delFlag").equals(Constants.SUCCESS)).collect(Collectors.toList());
            rollVo.setWinningList(winningMapList);

//            if (StringUtils.isNotEmpty(userId)) {
            if (winningMapList.size() > 0) {
                if (StringUtils.isNotEmpty(userId)) {
                    List<Map> currentUser = userMapList.stream().filter(map -> map.get("userId").equals(userId)).collect(Collectors.toList());
                    List<Map> oneselfWinningMapList = winningMapList.stream().filter(map -> userId.equals(map.get("userId").toString())).collect(Collectors.toList());
                    rollVo.setOneselfWinningList(oneselfWinningMapList);
                    if(currentUser.size()>0){
                        if(oneselfWinningMapList.size()>0){
                            rollVo.setUserWinningStatus(Constants.ROLLSTATUS0);
                        }else {
                            rollVo.setUserWinningStatus(Constants.ROLLSTATUS1);
                        }
                    }else {
                        rollVo.setUserWinningStatus(Constants.ROLLSTATUS2);
                    }
                }
                /**设置中奖的饰品的用户头像*/
                if (goodsList.size() > 0) {
                    winningMapList.stream().forEach(bean -> {
                        String prizeId = bean.get("prizeId").toString();
                        for (TGoods bean1 : goodsList) {
                            if (bean1.getGoodsId().equals(prizeId)) {
                                bean1.setUserPic(bean.get("userPic").toString());
                                bean1.setUserName(bean.get("userName").toString());
                                break;
                            }
                        }
                    });
                }
            }
//            }
        }
        if(rollVo.getUserCyList() != null && rollVo.getUserCyList().size()>0){
            List<Map> userMapList1 = rollVo.getUserCyList();
            userMapList1.stream().forEach(bean -> {
                bean.remove("userId");
            });
            rollVo.setUserCyList(userMapList1);
        }

        if(rollVo.getWinningList() != null && rollVo.getWinningList().size()>0){
            List<Map> winlist = rollVo.getWinningList();
            winlist.stream().forEach(bean -> {
                bean.remove("userId");
            });
            rollVo.setWinningList(winlist);
        }

        rollVo.setGoodsList(goodsList);
        rollVo.setRollPwd(null);
        return Response.success(rollVo);
    }

    ;
    /**
     * 用户参与ROLL房间
     * @param rollId
     * @param userId
     * @return
     */
    @Override
    public Response joinRoll(String rollId, String userId,String rollPwd) {
        if (StringUtils.isEmpty(rollId) || StringUtils.isEmpty(userId)) {
            return Response.fail(Constants.FAILCODE,"参数不能为空！");
        }
        /**获取ROLL房信息*/
        TRoll tRoll =  tRollMapper.selectTRollById(rollId);
        if (tRoll == null) {
            return Response.fail(Constants.FAILCODE,"ROLL参数错误，未找到对应数据！");
        }
        if(StringUtils.isEmpty(rollPwd) && Constants.ROLLMKTYPE6.equals(tRoll.getRollMkType())){
            return Response.fail(Constants.FAILCODE,"ROLL房密码不能为空");
        }

        if(tRoll.getRollMkType().equals(Constants.ROLLMKTYPE6) && !tRoll.getRollPwd().equals(rollPwd)){
            return Response.fail(Constants.FAILCODE,"ROLL房密码错误");
        }

        if (tRoll.getRollStatus().equals(Constants.ROLLSTATUS2)) {
            return Response.fail(Constants.FAILCODE,"ROLL已结束！");
        }
        /**获取用户信息*/
        TUser tUser = tUserMapper.selectTUserById(userId);
        if (tUser == null || (!tUser.getDelFlag().equals(Constants.SUCCESS))) {
            return Response.fail(Constants.FAILCODE,"用户不存在或已被停用！");
        }

        /**判断用户是否参与该ROLL房间*/
        Long userCount = tRollCyMapper.selectTRollCyUserCount(userId, rollId);
        if (userCount > 0l) {
            return Response.fail(Constants.FAILCODE,"用户已参与！");
        }
        String num = tRoll.getCyNumberlimit();
        if (StringUtils.isNotEmpty(num) && tRoll.getDrawPriceType().equals("1")) {
            Map<String, Long> ma = tRollCyMapper.countUserNumByRollId(tRoll.getRollId());
            if (Long.parseLong(num) <= ma.get("userNum")) {
                return Response.fail(Constants.FAILCODE, "参与人数已达上限！");
            }
        }

        /**获取加入门槛类型*/
        /**
         * ROLL房门槛类型 ROLL房门槛类型 0 无门槛 1 关注门槛 2 充值总额门槛 3 时间段内充值门槛 4 关注门槛+充值总额门槛
         * 5 关注门槛+时间段内充值门槛 6密码 7时间段注册门槛
         */
        String mktype = tRoll.getRollMkType();
        /**判断用户是否能加入ROLL房*/
        boolean flag = false;
        if (Constants.ROLLMKTYPE0.equals(mktype)) {
            flag = true;
        }
        /**推广用户*/
        TUser tgUser = null;
        if(Constants.ROLLMKTYPE1.equals(mktype) || Constants.ROLLMKTYPE4.equals(mktype)
                || Constants.ROLLMKTYPE5.equals(mktype) || Constants.ROLLMKTYPE8.equals(mktype)){
            tgUser = tUserMapper.selectTUserById(tUser.getUserPromotersId());
        }
        if (Constants.ROLLMKTYPE1.equals(mktype)) {
            /**判断该用户的推广人的推广码是否为此ROLL的关注推广码*/
            if (StringUtils.isNotEmpty(tUser.getUserPromotersId())){
                if(tgUser != null){
                    if (tRoll.getRollGzMk().equalsIgnoreCase(tgUser.getUserSelfCode())) {
                        flag = true;
                    }
                }

            }

        }
        if (Constants.ROLLMKTYPE2.equals(mktype)) {
            /**判断该用户的充值总额是否达到加入ROLL房标准*/
            if (tUser.getUserTotalRecharge().compareTo(tRoll.getRollCzMk()) >= 0) {
                flag = true;
            }
        }

        /**获取用户时间范围内的充值信息*/
        if (Constants.ROLLMKTYPE3.equals(mktype)) {
            /**时间范围内充值门槛*/
            BigDecimal money = tRechargeMapper.czMoneyCountByUserId(userId, tRoll.getRollStartTime(), tRoll.getRollEndTime());
            money = money == null ? new BigDecimal(0) : money;
            if (money.compareTo(tRoll.getRollFwczMk()) >= 0) {
                flag = true;
            }
        }
        if (Constants.ROLLMKTYPE4.equals(mktype)) {
            /**关注门槛+主播带动充值总额门槛*/
            if (tgUser != null) {
                if (tRoll.getRollGzMk().equalsIgnoreCase(tgUser.getUserSelfCode())) {
                    /**获取主播带动充值门槛*/
                    BigDecimal money = tRechargeMapper.czMoneyCountTGByUserId(userId, tUser.getUserPromotersId(), null, null);
                    if(money.compareTo(tRoll.getRollCzMk()) >= 0){
                        flag = true;
                    }
                }
            }
        }
        if (Constants.ROLLMKTYPE5.equals(mktype)) {
            /**关注门槛+时间范围内充值门槛*/
            if (tgUser != null) {
                if (tRoll.getRollGzMk().equalsIgnoreCase(tgUser.getUserSelfCode())) {
                    /**主播带动的时间范围内充值*/
                    BigDecimal money = tRechargeMapper.czMoneyCountTGByUserId(userId, tUser.getUserPromotersId(),tRoll.getRollStartTime(), tRoll.getRollEndTime());
                    if (money.compareTo(tRoll.getRollFwczMk()) >= 0){
                        flag = true;
                    }

                }
            }
        }

        if (Constants.ROLLMKTYPE6.equals(mktype)) {
            /**门槛密码*/
            if (tRoll.getRollPwd().equals(rollPwd)) {
                flag = true;
            }
        }
        if(Constants.ROLLMKTYPE7.equals(mktype)){
            /*判断当前用户注册时间是否在注册时间段内*/
            Date rollStartTime = tRoll.getRollStartTime();
            Date rollEndTime = tRoll.getRollEndTime();
            Date userCreateTime = tUser.getCreateTime();
            if(rollEndTime != null && rollEndTime != null && userCreateTime != null){
                if(userCreateTime.compareTo(rollStartTime) >= 0 && userCreateTime.compareTo(rollEndTime) < 1){
                    flag = true;
                }
            }
        }

        if(Constants.ROLLMKTYPE8.equals(mktype)){
            /*判断当前用户注册时间是否在注册时间段内 并且是否是此关注门槛*/
            Date rollStartTime = tRoll.getRollStartTime();
            Date rollEndTime = tRoll.getRollEndTime();
            Date userCreateTime = tUser.getCreateTime();
            if(rollEndTime != null && rollEndTime != null && userCreateTime != null){
                if(userCreateTime.compareTo(rollStartTime) >= 0 && userCreateTime.compareTo(rollEndTime) < 1){
                    if (StringUtils.isNotEmpty(tUser.getUserPromotersId())){
                        if(tgUser != null){
                            if (tRoll.getRollGzMk().equalsIgnoreCase(tgUser.getUserSelfCode())) {
                                flag = true;
                            }
                        }

                    }
                }
            }
        }

        /**用户满足加入ROLL房条件*/
        if (flag) {
            /**插入ROLL房参与表*/
            TRollCy tRollCy = new TRollCy();
            tRollCy.setUserId(tUser.getUserId());
            tRollCy.setRollId(tRoll.getRollId());
            tRollCy.setCreateTime(DateUtils.getNowDate());
            tRollCy.setDelFlag(Constants.FAIL);//默认插入没中奖
            tRollCyMapper.insertTRollCy(tRollCy);
        }else {
            return Response.fail(Constants.FAILCODE,"用户不满足参与条件！");

        }
        return getRollInfo(userId,rollId);
    }

    @Override
    public Response joinRollRobot(String rollId, String userId,String rollPwd) {
        if (StringUtils.isEmpty(rollId) || StringUtils.isEmpty(userId)) {
            return Response.fail(Constants.FAILCODE,"参数（ROLL房ID或用户ID）不能为空！");
        }
        /**获取ROLL房信息*/
        TRoll tRoll =  tRollMapper.selectTRollById(rollId);
        if (tRoll == null) {
            return Response.fail(Constants.FAILCODE,"ROLL参数错误，未找到对应数据！");
        }
        if (tRoll.getRollStatus().equals(Constants.ROLLSTATUS2)) {
            return Response.fail(Constants.FAILCODE,"ROLL已结束！");
        }
        /**获取用户信息*/
        TUser tUser = tUserMapper.selectTUserById(userId);
        if (tUser == null || (!tUser.getDelFlag().equals(Constants.SUCCESS))) {
            return Response.fail(Constants.FAILCODE,"用户不存在或已被停用！");
        }

        /**判断用户是否参与该ROLL房间*/
        Long userCount = tRollCyMapper.selectTRollCyUserCount(userId, rollId);
        if (userCount > 0l) {
            return Response.fail(Constants.FAILCODE,"用户已参与！");
        }

        String num = tRoll.getCyNumberlimit();
        if (StringUtils.isNotEmpty(num) && tRoll.getDrawPriceType().equals("1")) {
            Map<String, Long> ma = tRollCyMapper.countUserNumByRollId(tRoll.getRollId());
            if (Long.parseLong(num) <= ma.get("userNum")) {
                return Response.fail(Constants.FAILCODE, "参与人数已达上限！");
            }
        }
        /**插入ROLL房参与表*/
        TRollCy tRollCy = new TRollCy();
        tRollCy.setUserId(tUser.getUserId());
        tRollCy.setRollId(tRoll.getRollId());
        tRollCy.setCreateTime(DateUtils.getNowDate());
        tRollCy.setDelFlag(Constants.FAIL);//默认插入没中奖
        tRollCyMapper.insertTRollCy(tRollCy);
        return Response.success();
    }

//    /**
//     * ROLL房开奖
//     * @param list
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    @Async(value = "threadPoolTaskExecutor")
//    public void automaticLottery(TRoll tRoll) throws Exception{
//       /**获取该ROLL房下所有的饰品信息*/
//        List<TGoods> tGoodsList = tGoodsMapper.rollGoodsList(tRoll.getRollId());
//
//       /**获取该ROLL房下所有的参与者信息*/
//        List<TRollCy> tRollCyList = tRollCyMapper.getTRollCyInfoListByRollId(tRoll.getRollId());
//
//        log.info("{}:饰品个数为：{}，参与人数为：{}",tRoll.getRollName(),tGoodsList.size(),tRollCyList.size());
//
//        /**中奖名单*/
//        List<TRollCy> pparamList = new ArrayList<>();
//
//        /**用户金额变动记录*/
//        List<TBalanceChange> tBalanceChangeList = new ArrayList<>();
//
//       /**奖品、参与人数都不为0，否则没必要参与开奖了*/
//       if (tGoodsList.size() > 0 && tRollCyList.size()>0 )
//       {
//           /**筛选出指定饰品的参与者信息*/
//           List<TRollCy> appointtRollCyList = tRollCyList.stream().filter(bean -> bean.getAppointGoodsId() != null).collect(Collectors.toList());
//           /**对指定饰品的参与者信息单独开奖*/
//           if (appointtRollCyList.size()>0)
//           {
//               for (TRollCy tRollCy : appointtRollCyList)
//               {
//                   List<TGoods> tGoodsList1 = tGoodsList.stream().filter(bean -> tRollCy.getAppointGoodsId().equals(bean.getGoodsId())).collect(Collectors.toList());
//                   if (tGoodsList1.size() > 0){
//                       TGoods tGoods = tGoodsList1.get(0);
//                       /**设置抽中的商品*/
//                       tRollCy.setPrizeId(tGoods.getGoodsId());
//                       tRollCy.setPrizeName(tGoods.getGoodsName());
//                       tRollCy.setPrizePic(tGoods.getGoodsPic());
//                       tRollCy.setGoodsPrice(tGoods.getGoodsPrice());
//                       tRollCy.setGoodsExprice(tGoods.getGoodsExprice());
//                       tRollCy.setDelFlag(Constants.SUCCESS);
//                       tRollCy.setUpdateTime(DateUtils.getNowDate());
//                       tRollCy.setGoodsType(tGoods.getGoodsType());
//                       tRollCy.setPrizeGrate(tGoods.getGoodsGrate());
//                       /**添加指定开奖用户到中奖名单中*/
//                       pparamList.add(tRollCy);
//                       /**移除已经开奖的用户*/
//                       tRollCyList.remove(tRollCy);
//                       /**移出已经开奖的饰品*/
//                       tGoodsList.remove(tGoods);
//                   }
//               }
//           }
//
//           /**循环数量小的，随机获取用户对应的饰品*/
//           Random random = new Random();
//           int num = 0;
//           if (tGoodsList.size()>tRollCyList.size())
//           {
//               num = tRollCyList.size();
//           }else {
//               num = tGoodsList.size();
//           }
//
//           /**奖品、参与人数都不为0，否则没必要参与开奖了*/
//           if (tRollCyList.size() > 0  && tGoodsList.size()>0)
//           {
//               for (int i=0;i<num;i++)
//               {
//                   /**乱序后随机抽取*/
//                   Collections.shuffle(tRollCyList);
//                   int index = random.nextInt(tRollCyList.size());
//                   TRollCy tRollCy = tRollCyList.get(index);
//
//                   Collections.shuffle(tGoodsList);
//                   int index1 = random.nextInt(tGoodsList.size());
//                   TGoods tGoods = tGoodsList.get(index1);
//
//                   /**设置抽中的商品*/
//                   tRollCy.setPrizeId(tGoods.getGoodsId());
//                   tRollCy.setPrizeName(tGoods.getGoodsName());
//                   tRollCy.setPrizePic(tGoods.getGoodsPic());
//                   tRollCy.setGoodsPrice(tGoods.getGoodsPrice());
//                   tRollCy.setGoodsExprice(tGoods.getGoodsExprice());
//                   tRollCy.setDelFlag(Constants.SUCCESS);
//                   tRollCy.setUpdateTime(DateUtils.getNowDate());
//                   tRollCy.setGoodsType(tGoods.getGoodsType());
//                   tRollCy.setPrizeGrate(tGoods.getGoodsGrate());
//                   /**添加指定开奖用户到中奖名单中*/
//                   pparamList.add(tRollCy);
//                   /**移除已经开奖的用户、奖品*/
//                   tRollCyList.remove(index);
//                   tGoodsList.remove(index1);
//               }
//           }
//
//           /**背包表列表*/
//           List<TBackpack> backpackList = new ArrayList<>();
//
//           /**批量更新数据*/
//           for (int i=0;i<pparamList.size();i++)
//           {
//               TRollCy tRollCy = pparamList.get(i);
//               /**更新ROLL房参与者中奖信息*/
//               int count =  tRollCyMapper.updateTRollCy(tRollCy);
//               if (count == 0){
//                   throw new Exception("更新中奖信息失败！");
//               }
//               /**获取中奖用户信息*/
//               TUser user = tUserMapper.selectTUserById(tRollCy.getUserId());
//               /**中奖饰品添加到用户背包*/
//               String bbId = DateUtils.dateTimeNow()+ IdUtils.fastUUID().substring(0,8);
//               /**添加背包表*/
//               TBackpack backpack = new TBackpack();
//               backpack.setBbId(bbId);
//               backpack.setUserId(tRollCy.getUserId());
//               backpack.setGoodsId(tRollCy.getPrizeId());
//               backpack.setGoodsBelongingType(Constants.GOOGSBLTYPE1);
//               backpack.setGoodsBelongingId(tRollCy.getRollId());
//               backpack.setGoodsBelongingName(tRoll.getRollName());
//               backpack.setGoodsPrice(tRollCy.getGoodsPrice());
//               backpack.setGoodsExprice(tRollCy.getGoodsExprice());
//               backpack.setDelFlag(Constants.SUCCESS);
//               backpack.setCreateTime(DateUtils.getNowDate());
//               backpack.setGoodsNum(1);
//               backpack.setGoodsType(tRollCy.getGoodsType());
//               backpack.setUserPromotersId(user.getUserPromotersId());
//               backpack.setOpenBoxPrice(new BigDecimal("0"));
//               backpack.setBbGoodsName(tRollCy.getPrizeName());
//               backpack.setBbGoodsPic(tRollCy.getPrizePic());
//               backpack.setBbGoodsGrate(tRollCy.getPrizeGrate());
//               /***设置用户前后余额*/
//               backpack.setOpenBeforeBalance(user.getUserBalance());
//               /**判断中奖饰品是否为金币*/
//                if (tRollCy.getGoodsType().equals("4"))
//                {
//                    backpack.setBbStatus(Constants.BBSTATUS3);
//                    backpack.setOpenAfterBalance(user.getUserBalance().add(tRollCy.getGoodsExprice()));
//                    /**人工审核状态设置为已兑换状态*/
//                    backpack.setAuditStatus(Constants.AUDITSTATUS5);
//                }else {
//                    backpack.setAuditStatus(Constants.AUDITSTATUS0);
//                    backpack.setBbStatus(Constants.BBSTATUS0);
//                    backpack.setOpenAfterBalance(user.getUserBalance());
//                }
//               backpackList.add(backpack);
//
//               if (tRollCy.getGoodsType().equals("4"))
//               {
//                   /**插入兑换表*/
//                   TExchange tExchange = new TExchange();
//                   tExchange.setUserId(tRollCy.getUserId());
//                   tExchange.setGoodsId(tRollCy.getPrizeId());
//                   tExchange.setGoodsExprice(tRollCy.getGoodsExprice());
//                   tExchange.setGoodsName(tRollCy.getPrizeName());
//                   tExchange.setDhBeforeBalance(user.getUserBalance());
//                   /**增加兑换金币*/
//                   BigDecimal openAfterBalance = user.getUserBalance().add(tRollCy.getGoodsExprice());
//                   tExchange.setDhAfterBalance(openAfterBalance);
//                   tExchange.setCreateTime(DateUtils.getNowDate());
//                   tExchange.setDelFlag(Constants.SUCCESS);
//                   tExchange.setBbId(bbId);
//
//                   TBalanceChange balanceChange = new TBalanceChange();
//                   balanceChange.setBalanceBefore(user.getUserBalance());
//                   balanceChange.setBalanceAfter(openAfterBalance);
//                   balanceChange.setFee(tRollCy.getGoodsExprice());
//                   balanceChange.setUserId(user.getUserId());
//                   balanceChange.setFrequency(1);
//                   balanceChange.setCorrespondingid(tRoll.getRollId());
//                   balanceChange.setOperationType(Constants.OPERATIONTYPE8);
//                   balanceChange.setCreateTime(DateUtils.getNowDate());
//
//                   int excount = tExchangeMapper.insertTExchange(tExchange);
//                   if (excount == 0) {
//                       throw  new Exception("插入兑换信息失败！");
//                   }
//
//                   tBalanceChangeList.add(balanceChange);
//                   /**修改用户的余额*/
//                   user.setUserBalance(openAfterBalance);
//                   user.setUpdateTime(DateUtils.getNowDate());
//                   int row1 = tUserMapper.updateTUserBalance(user);
//                   if (row1 == 0) {
//                       throw  new Exception("用户信息修改失败！");
//                   }
//               }
//           }
//           /**批量插入背包信息表*/
//           int row2= tBackpackMapper.insertTBackpackBatch(backpackList);
//           if (row2 != backpackList.size()) {
//               throw new Exception("背包信息更新失败！");
//           }
//           log.info("{}:插入背包的数量{}",tRoll.getRollName(),backpackList.size());
//       }
//        /**更新ROLL房状态*/
//        tRoll.setUpdateTime(DateUtils.getNowDate());
//        tRoll.setRollStatus(Constants.ROLLSTATUS2);
//        int row3 = tRollMapper.updateRollStatusById(tRoll);
//        if (row3 == 0) {
//            throw new Exception("ROLL房信息就之前已更新！");
//        }
//        if(tBalanceChangeList.size() > 0){
//            Integer integer = tBalanceChangeMapper.insertTBalanceChangeBatch(tBalanceChangeList);
//        }
//        log.info(tRoll.getRollId()+"--开奖成功");
//
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async(value = "threadPoolTaskExecutor")
    public void automaticLotteryHash(TRoll tRoll) throws Exception {
        /**获取该ROLL房下所有的饰品信息*/
        List<TGoods> tGoodsList = tGoodsMapper.rollGoodsList(tRoll.getRollId());

        /**获取该ROLL房下所有的参与者信息*/
        List<TRollCy> cyList = tRollCyMapper.getTRollCyInfoListByRollId(tRoll.getRollId());

        log.info("{}:饰品个数为：{}，参与人数为：{}",tRoll.getRollName(),tGoodsList.size(),cyList.size());

        /**用户金额变动记录*/
        List<TBalanceChange> tBalanceChangeList = new ArrayList<>();

        /**奖品、参与人数都不为0，否则没必要参与开奖了*/
        if (tGoodsList.size() > 0 && cyList.size()>0 )
        {
            int num = 0;
            if (tGoodsList.size()>cyList.size())
            {
                num = cyList.size();
            }else {
                num = tGoodsList.size();
            }
            cyList.stream().forEach(bean -> {
                /**服务端种子*/
                String serverSeed = tRoll.getServerSeed();
                /**随机整数*/
                int nonce = HashUtil.generateNonce();
                /**公共hash*/
                String commonHash = HashUtil.commonHashCode(bean.getUserSeed1(),serverSeed,nonce);
                /**roll值*/
                Long rollValue = HashUtil.rollValue1(commonHash);

                bean.setServerSeed(serverSeed);
                bean.setNonce(nonce);
                bean.setCommonHash(commonHash);
                bean.setRollValue(rollValue);
                bean.setUserSeed(bean.getUserSeed1());
            });
            List<TRollCy> sortedList = cyList.stream()
                    .sorted(Comparator.comparingLong(TRollCy::getRollValue))
                    .collect(Collectors.toList());


            final int jpnum =num;
            IntStream.range(0, sortedList.size())
                    .forEach(index -> {
                        TRollCy tRollCy = sortedList.get(index);
                        if(index < jpnum){
                            TGoods tGoods = tGoodsList.get(index);

                            /**设置抽中的商品*/
                            tRollCy.setPrizeId(tGoods.getGoodsId());
                            tRollCy.setPrizeName(tGoods.getGoodsName());
                            tRollCy.setPrizePic(tGoods.getGoodsPic());
                            tRollCy.setGoodsPrice(tGoods.getGoodsPrice());
                            tRollCy.setGoodsExprice(tGoods.getGoodsExprice());
                            tRollCy.setDelFlag(Constants.SUCCESS);
                            tRollCy.setUpdateTime(DateUtils.getNowDate());
                            tRollCy.setGoodsType(tGoods.getGoodsType());
                            tRollCy.setPrizeGrate(tGoods.getGoodsGrate());
                        }
                    });

            /**背包表列表*/
            List<TBackpack> backpackList = new ArrayList<>();

            for (TRollCy tRollCy : sortedList) {
                /**更新ROLL房参与者中奖信息*/
                int count =  tRollCyMapper.updateTRollCy(tRollCy);
                if (count == 0){
                    throw new Exception("更新中奖信息失败！");
                }
                /**中奖用户*/
                if(Constants.SUCCESS.equals(tRollCy.getDelFlag())){
                    /**获取中奖用户信息*/
                    TUser user = tUserMapper.selectTUserById(tRollCy.getUserId());
                    /**中奖饰品添加到用户背包*/
                    String bbId = DateUtils.dateTimeNow()+ IdUtils.fastUUID().substring(0,8);
                    /**添加背包表*/
                    TBackpack backpack = new TBackpack();
                    backpack.setBbId(bbId);
                    backpack.setUserId(tRollCy.getUserId());
                    backpack.setGoodsId(tRollCy.getPrizeId());
                    backpack.setGoodsBelongingType(Constants.GOOGSBLTYPE1);
                    backpack.setGoodsBelongingId(tRollCy.getRollId());
                    backpack.setGoodsBelongingName(tRoll.getRollName());
                    backpack.setGoodsPrice(tRollCy.getGoodsPrice());
                    backpack.setGoodsExprice(tRollCy.getGoodsExprice());
                    backpack.setDelFlag(Constants.SUCCESS);
                    backpack.setCreateTime(DateUtils.getNowDate());
                    backpack.setGoodsNum(1);
                    backpack.setGoodsType(tRollCy.getGoodsType());
                    backpack.setUserPromotersId(user.getUserPromotersId());
                    backpack.setOpenBoxPrice(new BigDecimal("0"));
                    backpack.setBbGoodsName(tRollCy.getPrizeName());
                    backpack.setBbGoodsPic(tRollCy.getPrizePic());
                    backpack.setBbGoodsGrate(tRollCy.getPrizeGrate());
                    backpack.setOpenBeforeBalance(user.getUserBalance());
                    backpack.setOpenAfterBalance(user.getUserBalance());
                    /**判断中奖饰品是否为金币*/
                    if (tRollCy.getGoodsType().equals("4"))
                    {
                        backpack.setBbStatus(Constants.BBSTATUS3);
                        /**人工审核状态设置为已兑换状态*/
                        backpack.setAuditStatus(Constants.AUDITSTATUS5);
                    }else {
                        backpack.setAuditStatus(Constants.AUDITSTATUS0);
                        backpack.setBbStatus(Constants.BBSTATUS0);
                    }
                    backpack.setUserSeed(tRollCy.getUserSeed());
                    backpack.setServerSeed(tRollCy.getServerSeed());
                    backpack.setCommonHash(tRollCy.getCommonHash());
                    backpack.setNonce(tRollCy.getNonce());
                    backpack.setRollValue(tRollCy.getRollValue());
                    backpackList.add(backpack);

                    /**用户紫钻*/
                    BigDecimal openAfterSecondCurrency = user.getSecondCurrency();
                    TBalanceChange balanceChange = new TBalanceChange();
                    balanceChange.setBalanceBefore(user.getUserBalance());
                    balanceChange.setBalanceAfter(user.getUserBalance());
                    balanceChange.setFee(BigDecimal.ZERO);
                    balanceChange.setUserId(user.getUserId());
                    balanceChange.setFrequency(1);
                    balanceChange.setCorrespondingid(tRoll.getRollId());
                    balanceChange.setOperationType(Constants.OPERATIONTYPE8);
                    balanceChange.setCreateTime(DateUtils.getNowDate());
                    balanceChange.setSecondCurrencyBefore(openAfterSecondCurrency);

                    if (tRollCy.getGoodsType().equals("4"))
                    {
                        /**变动余额*/
                        balanceChange.setFee(tRollCy.getGoodsPrice());
                        openAfterSecondCurrency = openAfterSecondCurrency.add(tRollCy.getGoodsPrice());
                        /**插入兑换表*/
                        TExchange tExchange = new TExchange();
                        tExchange.setUserId(tRollCy.getUserId());
                        tExchange.setGoodsId(tRollCy.getPrizeId());
                        tExchange.setGoodsExprice(tRollCy.getGoodsPrice());
                        tExchange.setGoodsName(tRollCy.getPrizeName());
                        tExchange.setDhBeforeBalance(user.getSecondCurrency());
                        /**增加兑换金币*/
                        tExchange.setDhAfterBalance(openAfterSecondCurrency);
                        tExchange.setCreateTime(DateUtils.getNowDate());
                        tExchange.setDelFlag(Constants.SUCCESS);
                        tExchange.setBbId(bbId);

                        int excount = tExchangeMapper.insertTExchange(tExchange);
                        if (excount == 0) {
                            throw  new Exception("插入兑换信息失败！");
                        }

                        /**修改用户紫钻*/
                        user.setSecondCurrency(openAfterSecondCurrency);
                        user.setUpdateTime(DateUtils.getNowDate());
                        int row1 = tUserMapper.updateTUserBalance(user);
                        if (row1 == 0) {
                            throw  new Exception("用户信息修改失败！");
                        }
                    }

                    balanceChange.setSecondCurrencyAfter(openAfterSecondCurrency);
                    balanceChange.setConsumeValue(BigDecimal.ZERO);
                    balanceChange.setProfitPrice(tRollCy.getGoodsPrice());
                    balanceChange.setCostFee(BigDecimal.ZERO);
                    tBalanceChangeList.add(balanceChange);

                }
            }
            /**批量插入背包信息表*/
            int row2= tBackpackMapper.insertTBackpackBatch(backpackList);
            if (row2 != backpackList.size()) {
                throw new Exception("背包信息更新失败！");
            }
            log.info("{}:插入背包的数量{}",tRoll.getRollName(),backpackList.size());
        }
        /**更新ROLL房状态*/
        tRoll.setUpdateTime(DateUtils.getNowDate());
        tRoll.setRollStatus(Constants.ROLLSTATUS2);
        int row3 = tRollMapper.updateRollStatusById(tRoll);
        if (row3 == 0) {
            throw new Exception("ROLL房信息就之前已更新！");
        }
        if(tBalanceChangeList.size() > 0){
            Integer integer = tBalanceChangeMapper.insertTBalanceChangeBatch(tBalanceChangeList);
        }
        log.info(tRoll.getRollId()+"--开奖成功");
    }

    /**
     * 上线
     * @param rollIds
     * @return
     */
    @Override
    public int goOnline(String[] rollIds) {
        return tRollMapper.updateTRollStatusByIds(Constants.ROLLSTATUS1,rollIds);
    }

    /**
     * 结束
     * @param rollIds
     * @return
     */
    @Override
    public int closure(String[] rollIds) {
        return tRollMapper.updateTRollStatusByIds(Constants.ROLLSTATUS0,rollIds);
    }

    /**
     * ROLL房统计
     * @return
     */
    @Override
    public Map<String, Object> rollCount(String startTime, String endTime) {
        String stime = DateUtils.getDate() + " 00:00:00";
        String etime = DateUtils.getDate() + " 23:59:59";
        Map<String,Object> map  = tRollCyMapper.rollCount(startTime,endTime);
        Map<String,Object> map1 = tRollCyMapper.rollCount(stime,etime);
        map.put("outMoneyToday",map1.get("outMoney"));
        map.put("partakeNum",map1.get("partakeNum"));
        //今日取回
        Map<String,String> map2 = tBackpackMapper.rollRetrieveCountTotal();
        map.putAll(map2);
        return map;
    }

    @Override
    public List<TRollHomePageVo> selectHomePageDisplay() {
        List<TRollHomePageVo> tRollList = tRollMapper.selectHomePageDisplay();
        if (CollectionUtils.isEmpty(tRollList)) {
            return tRollList;
        }
        if (tRollList.size() > 0) {

            tRollList = tRollList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                                    () -> new TreeSet<>(Comparator.comparing(roll -> roll.getRollId()))
                            ),
                            ArrayList::new
                    )
            )
                    .stream().sorted(Comparator.comparing(TRollHomePageVo::getSort)
                    .thenComparing(TRollHomePageVo::getRollStatus)
                    .thenComparing(TRollHomePageVo::getRollZdkjTime))
                    .collect(Collectors.toList());

            List<String> rollIds = tRollList.stream().map(TRollHomePageVo::getRollId).collect(Collectors.toList());
            List<Map<String, Long>> userNumList = tRollCyMapper.countUserNumByRollIdBatch(rollIds);
            if (userNumList.size() > 0) {
                tRollList.forEach(rollBean -> {
                    List<Map<String, Long>> rollId = userNumList.stream().filter(usernum -> String.valueOf(usernum.get("rollId")).equals(rollBean.getRollId())).collect(Collectors.toList());
                    if (rollId.size() > 0) {
                        Long userNum = rollId.get(0).get("userNum") == null ? 0l : rollId.get(0).get("userNum");
                        rollBean.setUserNum(userNum.intValue());
                    }
                });
            }
        }
        return tRollList;
    }

    /**
     * 单独对数据进行关联配置  统计用户人数、饰品件数、饰品金额
     * @param rollList
     * @param tRoll
     * @return
     */
    private List<TRollVo> countTRollPageList(List<TRollVo> rollList,String userId){
        /**判断用户ID是否存在，存在则显示状态,*/
        /**用户加入房间的状态  0 未加入 1 已加入 2 已结束*/
        if (rollList.size() > 0) {
            List<String> rollIds = rollList.stream().map(TRollVo::getRollId).collect(Collectors.toList());

            List<TRollCy> tRollCyList = new ArrayList<>();
            /**获取用户参与ROLL房信息*/
            if (StringUtils.isNotEmpty(userId)) {
                tRollCyList = tRollCyMapper.selectTRollCyByUserId(userId, rollIds);
            }
            for (TRollVo bean : rollList) {
                if (Constants.ROLLSTATUS1.equals(bean.getRollStatus())) {
                    if (tRollCyList.size() > 0) {
                        List<TRollCy> tRollCyList1 = tRollCyList.stream().filter(tRollCy -> bean.getRollId().equals(tRollCy.getRollId())).collect(Collectors.toList());
                        if (tRollCyList1.size() > 0) {
                            if (Constants.ROLLSTATUS2.equals(bean.getRollStatus())) {
                                bean.setUserStatus(Constants.USERROLLSTATUS2);
                            } else {
                                bean.setUserStatus(Constants.USERROLLSTATUS1);
                            }
                            bean.setUserId(userId);
                        } else {/**表示未加入*/
                            bean.setUserStatus(Constants.USERROLLSTATUS0);
                        }
                    } else {
                        bean.setUserStatus(Constants.USERROLLSTATUS0);
                    }
                } else {
                    bean.setUserStatus(Constants.USERROLLSTATUS2);
                }
            }
            /**统计ROLL房用户参与人数统计*/
            List<Map> mapList = tRollCyMapper.countUserNumGroupRollId(rollIds);
            if (mapList.size() > 0) {
                rollList.stream().forEach(bean -> {
                    List<Map> mapList1 = mapList.stream().filter(map -> map.get("rollId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setUserNum(map.get("userNum").toString());
                    }else {
                        bean.setUserNum("0");
                    }
                });
            }else {
                rollList.stream().forEach(bean -> {
                    bean.setUserNum("0");
                });
            }
            /**统计ROLL房的饰品件数、奖池*/
            List<Map> goodsList = tGoodsMapper.countGoodsNumAndPrice(rollIds);
            if (goodsList.size() > 0) {
                rollList.stream().forEach(bean -> {
                    List<Map> mapList1 = goodsList.stream().filter(map -> map.get("goodsBelongingId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setGoodsCount(map.get("goodsCount").toString());
                        bean.setGoodsPriceTotal(map.get("goodsPriceTotal").toString());
                    }else {
                        bean.setGoodsCount("0");
                        bean.setGoodsPriceTotal("0");
                    }
                });
            }else {
                rollList.stream().forEach(bean -> {
                    bean.setGoodsCount("0");
                    bean.setGoodsPriceTotal("0");
                });
            }
            /**ROLL房对应的排名前三的饰品图片*/
            rollList.stream().forEach(bean -> {
                List<Map> list = tGoodsMapper.rollPicList3(bean.getRollId());
                bean.setList(list);
            });
        }
        return rollList;
    }

    /***
     * 查询我参与的列表
     * @param pageInfoParamVo
     * @return
     */
    @Override
    public List<TRollVo> selectMyRollPageList(PageInfoParamVo pageInfoParamVo) {
        String rollName = pageInfoParamVo.getRollName();
        String userId = pageInfoParamVo.getUserId();
        List<TRollVo> rollList = tRollMapper.selectTRollListByUser(rollName, userId);
        if (rollList.size() > 0) {
            List<String> rollIds = rollList.stream().map(TRollVo::getRollId).collect(Collectors.toList());
            /**统计ROLL房用户参与人数统计*/
            List<Map> mapList = tRollCyMapper.countUserNumGroupRollId(rollIds);
            if (mapList.size() > 0) {
                rollList.stream().forEach(bean -> {
                    List<Map> mapList1 = mapList.stream().filter(map -> map.get("rollId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setUserNum(map.get("userNum").toString());
                    } else {
                        bean.setUserNum("0");
                    }
                });
            } else {
                rollList.stream().forEach(bean -> {
                    bean.setUserNum("0");
                });
            }
            /**统计ROLL房的饰品件数、奖池*/
            List<Map> goodsList = tGoodsMapper.countGoodsNumAndPrice(rollIds);
            if (goodsList.size() > 0) {
                rollList.stream().forEach(bean -> {
                    List<Map> mapList1 = goodsList.stream().filter(map -> map.get("goodsBelongingId").toString().equals(bean.getRollId())).collect(Collectors.toList());
                    Map map = mapList1.size() > 0 ? mapList1.get(0) : null;
                    if (map != null) {
                        bean.setGoodsCount(map.get("goodsCount").toString());
                        bean.setGoodsPriceTotal(map.get("goodsPriceTotal").toString());
                    } else {
                        bean.setGoodsCount("0");
                        bean.setGoodsPriceTotal("0");
                    }
                });
            } else {
                rollList.stream().forEach(bean -> {
                    bean.setGoodsCount("0");
                    bean.setGoodsPriceTotal("0");
                });
            }
            /**ROLL房对应的排名前三的饰品图片*/
            rollList.stream().forEach(bean -> {
                List<Map> list = tGoodsMapper.rollPicList3(bean.getRollId());
                bean.setList(list);
            });
        }
        return rollList;
    }

    @Override
    public List<TRoll> robotRollList() {
        return tRollMapper.robotRollList();
    }
}
